
/**
 * 房间防御检查
 */
 export class TowerTask implements IRoomTask{
  run(room: Room): void {
    let enemyId: Id<Creep> | undefined = undefined;
    const myTowers = room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_TOWER } }) as StructureTower[];
  
    // 主动寻找房间内的敌人
    if (room.memory.enemys && room.memory.enemys.length > 0) {
      room.memory.enemys.forEach((e)=>{
        let tager = Game.getObjectById(e);
        if(tager){
          enemyId = e;
        }
      });
    } 
    else {
      room.memory.enemys = new Array<Id<Creep>>();
      const hostiles = room.find(FIND_HOSTILE_CREEPS);
      if (hostiles.length > 0) {
        hostiles.forEach(hostile => {
          room.memory.enemys.push(hostile.id);
        });
        enemyId = room.memory.enemys[0];
      }
    }
  
    for (const tower of myTowers) {
      // 优先攻击敌人
      if (enemyId) {
        const target = Game.getObjectById(enemyId);
        if (target && target instanceof Creep) {
          tower.attack(target);
        } 
      } else {

        const storage = room.storage;
        if (!storage) {
          return;
        }

        const energyThreshold = 0.3; // 能量储备阈值为 30%
        const energyAvailable = storage.store[RESOURCE_ENERGY];
        const energyCapacity = storage.store.getCapacity(RESOURCE_ENERGY);
        
        // 查找并且查看需要修复的建筑
        const myStructures = room.find(FIND_STRUCTURES);
        myStructures.forEach((structure)=>{
          
          if(structure.structureType === STRUCTURE_RAMPART || structure.structureType === STRUCTURE_WALL){
            // 能量储备 高于30% 才进行修复
            if ((energyAvailable / energyCapacity < energyThreshold)) {
              return;
            }
          }

          if(structure.hits < structure.hitsMax && structure.hits / structure.hitsMax < 0.1){
            tower.repair(structure);
          }
        });

      }
    }
  }
}